package com.song.ssm.month.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.song.ssm.month.mapper.UserMapper;
import com.song.ssm.month.pojo.Role;
import com.song.ssm.month.pojo.User;
import com.song.ssm.month.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 宋伟宁
 * @Date 2023/9/25
 * @Version 1.0
 **/
@Service
public class UserService implements IUserService {
    @Resource
    private UserMapper userMapper;


    @Override
    public User login(User user) {
        return this.userMapper.login(user.getUsername(),user.getPassword());
    }

//    @Override
//    public List<User> findUsers(User user) {
//        return this.userMapper.findUsers(user);
//    }

    @Override
    public PageInfo<User> page(Integer offset, Integer pagesize, User user) {
        PageHelper.startPage(offset,pagesize);
        return new PageInfo<>(this.userMapper.findUsers(user));
    }

    @Override
    public List<Role> roles() {
        return this.userMapper.roles();
    }

    @Override
    public boolean hashName(String username) {
        return this.userMapper.hashName(username)==1;
    }

    @Override
    public boolean save(User user) {
        System.out.println(user);
        int m = 0;
        if(user.getUid()==null || user.getUid()==0) {

            //插入用户表
            m = this.userMapper.addUser(user);
            //获取刚插入的自增长的id
            int uid = user.getUid();
            //插入中间
            m += this.userMapper.addMiddle(uid, user.getChk());
            return  m>=2;
        }else{
            //修改用户信息
             m = this.userMapper.updateUser(user);
             int uid= user.getUid();
            //删除中间表
            m += this.userMapper.deleteMiddle(uid);
            //插入中间表
            m += this.userMapper.addMiddle(uid, user.getChk());
           return m>=3;
        }

    }

    @Override
    public User findById(int id) {
        return this.userMapper.findById(id);
    }

    @Override
    public boolean status(int id) {
        return this.userMapper.status(id);
    }

    @Override
    public List<Integer> findRoles(int uid) {
        return this.userMapper.findRoles(uid);
    }

    @Override
    public boolean del(String ids) {
        int m=0;
        String[] arr = ids.split(",");
        //删除用户角色表
          m=this.userMapper.batch_middle(arr);
        //删除用户表
        m += this.userMapper.del_user(arr);
        return m>=2;
    }
}
